//
//  NSString+MyNSString.m
//  JHLNHV2
//
//  Created by macbook-air on 15/5/13.
//  Copyright (c) 2015年 macbook-air. All rights reserved.
//

#import "NSString+KNAddtion.h"
#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonCryptor.h>

@implementation NSString (KNAddtion)

+ (BOOL)KNIsNullOrEmpty:(NSString *)string {
    if (string) {
        if ([string isKindOfClass: [NSString class]]) {
            if (string.length == 0) {
                return YES;
            } else {
                
                if ([string isEqualToString:@"(null)"]){
                    return YES;
                }
                
                if ([string stringByReplacingOccurrencesOfString: @" " withString: @""].length == 0) {
                    return YES;
                } else {
                    return NO;
                }
                
                
            }
        } else {
            return YES;
        }
    } else {
        return YES;
    }
}
+ (NSString *)KNTimeStringFromInterval:(long)interval{
    NSMutableString *timeString=[[NSMutableString alloc]init];
    if (interval/86400>0) {
        [timeString appendString:[NSString stringWithFormat:@"%ld天",interval/86400]];
    }
    interval=interval%86400;
    if (interval/3600>0) {
        [timeString appendString:[NSString stringWithFormat:@"%ld小时",interval/3600]];
    }
    interval=interval%3600;
    if (interval/60>0) {
        [timeString appendString:[NSString stringWithFormat:@"%ld分",interval/60]];
    }
    interval=interval%60;
    [timeString appendString:[NSString stringWithFormat:@"%ld秒",interval]];
    return timeString;
}

- (NSString *)KNTrim{
    return [self stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]];
}

+ (BOOL)KNValidateCarNo:(NSString *)carNumber {
    NSString *carRegex = @"^[A-Za-z]{1}[A-Za-z_0-9]{5}$";
    NSPredicate *carTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",carRegex];
    return [carTest evaluateWithObject:carNumber];
}

- (NSString *)KNURLEncodedString
{
    NSString *encodedString = (NSString *)
    CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                              (CFStringRef)self,
                                                              (CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]",
                                                              NULL,
                                                              kCFStringEncodingUTF8));
    return encodedString;
}
+ (BOOL)KNIsPhone:(NSString *)phone
{
    NSString *regex = @"^(1)\\d{10}$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    return [pred evaluateWithObject:phone];
}
+ (BOOL)KNIsIDCardNumber:(NSString *)text{
    NSString *pattern = @"(^[0-9]{15}$)|([0-9]{17}([0-9]|X)$)";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",pattern];
    BOOL isMatch = [pred evaluateWithObject:text];
    return isMatch;
}
+ (NSString *)KNStringByRemovingControlCharacters: (NSString *)inputString
{
    NSCharacterSet *controlChars = [NSCharacterSet controlCharacterSet];
    NSRange range = [inputString rangeOfCharacterFromSet:controlChars];
    if (range.location != NSNotFound) {
        NSMutableString *mutable = [NSMutableString stringWithString:inputString];
        while (range.location != NSNotFound) {
            [mutable deleteCharactersInRange:range];
            range = [mutable rangeOfCharacterFromSet:controlChars];
        }
        return mutable;
    }
    return inputString;
}
+ (NSString *)KNGetTypeByLevel:(int)level{
    if (level==0) {
        return @"普通用户";
    }else if (level==1) {
        return @"市级合作商";
    }else if (level==2) {
        return @"省级合作商";
    }else {
        return @"召集人";
    }
}

//MD5 加密
+(NSString*)KNMd5Str:(NSString*)str
{
    NSString *md5str;
    const char *cStr = [str UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(cStr, (unsigned int)strlen(cStr), result);
    
    NSMutableString *hash = [NSMutableString string];
    for (int i = 0; i < 16; i++)
    {
        [hash appendFormat:@"%02X", result[i]];
    }
    md5str =  [hash lowercaseString];
    return md5str;
}

- (NSString *)KNMd5 {
    return [[self class] KNMd5Str:self];
}

+ (BOOL)KNIsValidMoney:(NSString *)string{
    if ([string floatValue]-0<0.0001) {
        return NO;
    }
    //最多两位小数
    NSString *regex1 = @"^\\d+(\\.{1}\\d{0,2})?$";
    NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex1];
    if([pred1 evaluateWithObject: string]){
        //排除以0d开头的情况
        NSString *regex2 = @"^0\\d+(\\.{1}\\d{0,2})?$";
        NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex2];
        if ([pred2 evaluateWithObject:string]) {
            return NO;
        }else{
            return YES;
        }
    }else {
        return NO;
    }
}

- (BOOL)KNIsAllNumber {
    if (self.length == 0) {
        return NO;
    }
    NSString *regex =@"[0-9]*";
    
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    
    return [pred evaluateWithObject:self];
}

- (BOOL)KNIsAllChars{
    if (self.length == 0) {
        return NO;
    }
    NSString *regex =@"[a-zA-Z]*";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    return  [pred evaluateWithObject:self];
}

+ (NSString *)KNGetDateStringWithSecond:(BOOL)withSecond byTimeInterval:(double)timeInterval{
    NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
    if (withSecond) {
        [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    }else{
        [formatter setDateFormat:@"yyyy-MM-dd"];
    }
    return [formatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:timeInterval]];
}

+ (NSMutableAttributedString *)KNRenderString:(NSString *)renderString withColor:(UIColor *)renderColor font:(UIFont *)font
{
    NSMutableAttributedString *mStr = [NSString KNRenderString:renderString withColor:renderColor];
    [mStr addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, renderString.length)];
    return mStr;
}

+ (NSMutableAttributedString *)KNRenderString:(NSString *)renderString withColor:(UIColor *)renderColor
{
    NSMutableAttributedString *mStr = [[NSMutableAttributedString alloc] initWithString:renderString];
    [mStr addAttribute:NSForegroundColorAttributeName value:renderColor range:NSMakeRange(0, renderString.length)];
    return mStr;
}

- (NSMutableAttributedString *)KNRenderString:(NSString *)renderString withColor:(UIColor *)renderColor
{
    NSMutableAttributedString *mStr = [[NSMutableAttributedString alloc] initWithString:self];
    [mStr addAttribute:NSForegroundColorAttributeName value:renderColor range:[self rangeOfString:renderString]];
    return mStr;
}

- (NSMutableAttributedString *)KNRenderString:(NSString *)renderString withColor:(UIColor *)renderColor font:(UIFont *)font
{
    NSMutableAttributedString *mStr = [self KNRenderString:renderString withColor:renderColor];
    [mStr addAttribute:NSFontAttributeName value:font range:[self rangeOfString:renderString]];
    return mStr;
}

- (NSString *)KNSafeSubstringWithRange:(NSRange)range {
    if (range.location != NSNotFound && range.location + range.length <= self.length) {
        return [self substringWithRange:range];
    }
    return @"";
}

- (NSString *)KNDeleteAllSpicalChar:(NSString *)spicalChar {
    return [self stringByReplacingOccurrencesOfString:spicalChar withString:@""];
}

- (NSString *)KNFormatPhoneNum:(NSString *)phone
{
    if ([phone hasPrefix:@"86"]) {
        NSString *formatStr = [phone substringWithRange:NSMakeRange(2, [phone length]-2)];
        return formatStr.KNTrim;
    }
    else if ([phone hasPrefix:@"+86"])
    {
        if ([phone hasPrefix:@"+86·"]) {
            NSString *formatStr = [phone substringWithRange:NSMakeRange(4, [phone length]-4)];
            return formatStr.KNTrim;
        }
        else
        {
            NSString *formatStr = [phone substringWithRange:NSMakeRange(3, [phone length]-3)];
            return formatStr.KNTrim;
        }
    }
    return [phone stringByReplacingOccurrencesOfString:@" " withString:@""];
}

- (NSString *)KNGetLastStrByLengh:(NSUInteger)len {
    if (len > self.length) {
        return @"";
    } else {
        return [self substringWithRange:NSMakeRange(self.length - len, len)];
    }
    return @"";
}

- (CGFloat)KNGetHeightWithMaxWidth:(CGFloat)width font:(UIFont *)font
{
    CGSize constraint = CGSizeMake(width, CGFLOAT_MAX);
    CGSize size;
    
    NSStringDrawingContext *context = [[NSStringDrawingContext alloc] init];
    CGSize boundingBox = [self boundingRectWithSize:constraint
                                            options:NSStringDrawingUsesLineFragmentOrigin
                                         attributes:@{NSFontAttributeName:font}
                                            context:context].size;
    
    size = CGSizeMake(ceil(boundingBox.width), ceil(boundingBox.height));
    
    return size.height;
}

+ (CGFloat)KNGetHeightForAttributedStringWithAttributedString:(NSAttributedString *)string width:(CGFloat)width {
    CGSize constraint = CGSizeMake(width, CGFLOAT_MAX);
    CGSize size;
    
    NSStringDrawingContext *context = [[NSStringDrawingContext alloc] init];
    CGSize boundingBox = [string boundingRectWithSize:constraint options:NSStringDrawingUsesLineFragmentOrigin context:context].size;
    
    size = CGSizeMake(ceil(boundingBox.width), ceil(boundingBox.height));
    
    return size.height;
}

- (NSDictionary *)KNUrlQueryStringToDict {
    NSArray *list = [self componentsSeparatedByString:@"&"];
    NSMutableDictionary *dict = @{}.mutableCopy;
    [list enumerateObjectsUsingBlock:^(NSString *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSArray *parms = [obj componentsSeparatedByString:@"="];
        [dict setObject:parms.lastObject forKey:parms.firstObject];
    }];
    return dict;
}

+ (BOOL)KNIsDecimal:(NSString *)inputString {
    if (inputString.length == 0)
        return NO;
    NSString *regex = @"^[0-9]+([.]{0,1}[0-9]+){0,1}$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    return [pred evaluateWithObject:inputString];
}
/**
 *  生成32位UUID
 */
+ (NSString *)KNUUIDString{
    
    CFUUIDRef uuid_ref = CFUUIDCreate(NULL);
    CFStringRef uuid_string_ref= CFUUIDCreateString(NULL, uuid_ref);
    NSString *uuid = [NSString stringWithString:(__bridge NSString *)uuid_string_ref];
    CFRelease(uuid_ref);
    CFRelease(uuid_string_ref);
    
    //去除UUID ”-“
    NSString *UUID = [[uuid lowercaseString] stringByReplacingOccurrencesOfString:@"-" withString:@""];
    return UUID;
}

@end

